package com.wangsd.web.api.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.wangsd.common.basicbean.MyController;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.WxMiniService;
import com.wangsd.common.component.WxpayService;
import com.wangsd.web.shop.entity.Customer;
import com.wangsd.web.shop.service.CouponService;
import com.wangsd.web.shop.service.CustomerService;
import com.wangsd.web.shop.service.TestService;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.service.SysCompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "测试接口")
@RestController
@RequestMapping("/api/test")
@Slf4j
public class TestController extends MyController {

    @Value("${notify_url}")
    private String notify_url;
    @Autowired
    SysCompanyService companyService;
    @Autowired
    CustomerService customerService;
    @Autowired
    TestService testService;
    @Autowired
    private CouponService couponService;

    @GetMapping("/testPay")
    public Result testPay(Integer price, String code) {
        Customer customer = customerService.selectByMiniAppid(this.getMiniAppid());
        WxMiniService wxMiniService = new WxMiniService(this.getMiniAppid(), customer.getMiniSecret());
        WxMaJscode2SessionResult data = wxMiniService.login(code);

        SysCompany company = companyService.selectByCode("1");
        WxpayService wxpayService = new WxpayService(company, "1534202201", null);
        JSONObject result = wxpayService.sendJsApi(System.currentTimeMillis() + "", price + "",
                notify_url + "/api/notify/wxPayBack", data.getOpenid());
        return Result.success(result);
    }

    @GetMapping("/test")
    public void test(Integer amount) {
        testService.save(amount);
    }

    /**
     * 小程序发券成功后处理逻辑
     * @param outTradeNo
     * @param couponCode
     * @return
     */
    @ApiOperation(value = "处理发券成功没有保存记录的问题")
    @GetMapping("/sendCouponSuccess")
    public Result sendCouponSuccess(String outTradeNo, String couponCode) {
        couponService.sendCouponSuccess(outTradeNo, couponCode);
        return Result.success();
    }
}
